<?php


namespace app\admin\controller\Video;


use app\admin\controller\BaseController;
use app\admin\model\Course\CourseModel;
use app\admin\model\User\UserModel;
use app\admin\model\Video\VideoCateRelationModel;
use app\admin\model\Video\VideoChapterModel;
use app\admin\model\Video\VideoCourseRelationModel;
use app\admin\model\Video\VideoGoodsRelationModel;
use app\admin\model\Video\VideoModel;
use app\admin\model\Video\VideoUserRelationModel;
use app\api\model\Goods\GoodsModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\facade\Db;
use think\Request;

class Video extends BaseController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getVideoList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = $param['page'];
        $limit = $param['limit'];
        $video_title = !empty($param['video_title']) ? $param['video_title'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }

        if (!empty($video_title)) {
            array_push($where, ['video_title', 'like', '%' . $video_title . '%']);
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 1]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 0]);
            }
        }
        $list = VideoModel::getVideoListWhere($page, $limit, $where);
        $count = VideoModel::getVideoCountWhere($where);
        foreach ($list as &$item) {
            $item['label'] = !empty($item['label']) ? implode(',', json_decode($item['label'], true)) : [];
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'], true) : [];
            foreach ($images as &$image) {
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";

            $chapters = VideoChapterModel::getVideoChapterWhereMore(['video_id' => $item['id']]);
            if (!empty($chapters)) {
                $item['chapters'] = $chapters;
            } else {
                $item['chapters'] = [];
            }
        }
        unset($item);

        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }

    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addVideo(Request $request)
    {
        $param = $request->param();
        $video_title = !empty($param['video_title']) ? $param['video_title'] : "";
        $label = !empty($param['label']) ? explode(',', trim($param['label'], ',')) : [];
        $brief = !empty($param['brief']) ? $param['brief'] : "";
        $play_default = !empty($param['play_default']) ? $param['play_default'] : 0;
        $school_id = !empty($param['school_id']) ? $param['school_id'] : 0;
        $is_recommend = !empty($param['is_recommend']) ? 1 : 0;
        $details = !empty($param['details']) ? json_encode($param['details']) : "";
        $sort = !empty($param['sort']) ? $param['sort'] : 0;
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        $data = [
            'video_title' => $video_title,
            'label' => json_encode($label),
            'brief' => $brief,
            'play_default' => $play_default,
            'school_id' => $school_id,
            'is_recommend' => $is_recommend,
            'details' => $details,
            'sort' => $sort,
            'up_time' => date("Y-m-d H:i:s", time()),
            'add_time' => date("Y-m-d H:i:s", time())
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/video/flv/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "/video/flv/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }

        if (!empty($url)) {
            $data['img'] = $url;
        }
        if (!empty($urls)) {
            $data['slider_img'] = json_encode($urls);
        }

        if (!empty($is_show) && $is_show == "on") {
            $data['is_show'] = 1;
        } else {
            $data['is_show'] = 0;
        }
        Db::startTrans();
        try {
            $id = VideoModel::addVideo($data);
            if ($id) {
                if (!empty($param['cate_ids'])) {
                    $cate_ids = explode(',', $param['cate_ids']);
                    $data = [];
                    foreach ($cate_ids as $cate_id) {
                        $arr['video_id'] = $id;
                        $arr['cate_id'] = $cate_id;
                        $arr['add_time'] = date("Y-m-d H:i:s", time());
                        array_push($data, $arr);
                    }
                    VideoCateRelationModel::addVideoCateRelation($data);
                }
                if (!empty($param['goods_ids'])) {
                    $goods_ids = explode(',', $param['goods_ids']);
                    $data = [];
                    foreach ($goods_ids as $goods_id) {
                        $arr['video_id'] = $id;
                        $arr['goods_id'] = $goods_id;
                        $arr['add_time'] = date("Y-m-d H:i:s", time());
                        array_push($data, $arr);
                    }
                    VideoGoodsRelationModel::addVideoGoodsRelation($data);
                }
                if (!empty($param['course_ids'])) {
                    $course_ids = explode(',', $param['course_ids']);
                    $data = [];
                    foreach ($course_ids as $course_id) {
                        $arr['video_id'] = $id;
                        $arr['course_id'] = $course_id;
                        $arr['add_time'] = date("Y-m-d H:i:s", time());
                        array_push($data, $arr);
                    }
                    VideoCourseRelationModel::addVideoCourseRelation($data);
                }
                //相关用户
                if (!empty($param['user_ids'])) {
                    $user_ids = explode(',', $param['user_ids']);
                    $user = [];
                    foreach ($user_ids as $user_id) {
                        $arr = [];
                        $arr['video_id'] = $id;
                        $arr['user_id'] = $user_id;
                        $arr['add_time'] = date("Y-m-d H:i:s", time());
                        array_push($user, $arr);
                    }
                    VideoUserRelationModel::addVideoRelation($user);
                }
                if (!empty($param['chap_title']) && !empty($param['chap_url'])) {
                    foreach ($param['chap_title'] as $k => $item) {
                        $chapter_arr = array(
                            'video_id' => $id,
                            'title' => !empty($param['chap_title'][$k]) ? $param['chap_title'][$k] : "",
                            'url' => !empty($param['chap_url'][$k]) ? $param['chap_url'][$k] : "",
                            'img' => !empty($param['chap_img'][$k]) ? $param['chap_img'][$k] : "",
                            'duration' => !empty($param['chap_duration'][$k]) ? $param['chap_duration'][$k] : "",
                            'play_num' => !empty($param['chap_play_num'][$k]) ? $param['chap_play_num'][$k] : 0,
                            'is_free' => !empty($param['chap_is_free'][$k]) ? 1 : 0,
                            'up_time' => date('Y-m-d H:i:s', time()),
                            'add_time' => date('Y-m-d H:i:s', time()),
                            'sort' => !empty($param['chap_sort'][$k]) ? $param['chap_sort'][$k] : 0,
                        );
                        $result = VideoChapterModel::addVideoChapter($chapter_arr);
                        if (empty($result)) {
                            Db::rollback();
                            return Util::returnJson(self::CODE_ERROR, null, "添加失败");
                        }
                    }
                }
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
            } else {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR, null, "添加失败");
            }
        } catch (\Exception $e) {
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editVideo(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $video_title = !empty($param['video_title']) ? $param['video_title'] : "";
        $label = !empty($param['label']) ? explode(',', trim(str_replace("，", ",", trim($param['label'])), ',')) : [];
        $brief = !empty($param['brief']) ? $param['brief'] : "";
        $play_default = !empty($param['play_default']) ? $param['play_default'] : 0;
        $school_id = !empty($param['school_id']) ? $param['school_id'] : 0;
        $is_recommend = !empty($param['is_recommend']) ? 1 : 0;
        $details = !empty($param['details']) ? json_encode($param['details']) : "";
        $sort = !empty($param['sort']) ? $param['sort'] : 0;
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if (empty($id)) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        $save = [
            'video_title' => $video_title,
            'label' => json_encode($label),
            'brief' => $brief,
            'play_default' => $play_default,
            'school_id' => $school_id,
            'is_recommend' => $is_recommend,
            'details' => $details,
            'sort' => $sort,
            'up_time' => date("Y-m-d H:i:s", time())
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/video/flv/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "/video/flv/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }

        if (!empty($url)) {
            $save['img'] = $url;
        }
        if (!empty($urls)) {
            $save['slider_img'] = json_encode($urls);
        }

        if (!empty($is_show) && $is_show == "on") {
            $save['is_show'] = 1;
        } else {
            $save['is_show'] = 0;
        }

        Db::startTrans();
        try {
            VideoModel::updateVideoWhere([['id', '=', $id]], $save);
            VideoCateRelationModel::delVideoCateRelationWhere([['video_id', '=', $id]]);
            VideoGoodsRelationModel::delVideoGoodsRelationWhere([['video_id', '=', $id]]);
            VideoCourseRelationModel::delVideoCourseRelationWhere([['video_id', '=', $id]]);
            if (!empty($param['cate_ids'])) {
                $cate_ids = explode(',', $param['cate_ids']);
                $cate = [];
                foreach ($cate_ids as $cate_id) {
                    $arr = [];
                    $arr['video_id'] = $id;
                    $arr['cate_id'] = $cate_id;
                    $arr['add_time'] = date("Y-m-d H:i:s", time());
                    array_push($cate, $arr);
                }
                VideoCateRelationModel::addVideoCateRelation($cate);
            }
            if (!empty($param['goods_ids'])) {
                $goods_ids = explode(',', $param['goods_ids']);
                $goods = [];
                foreach ($goods_ids as $goods_id) {
                    $arr = [];
                    $arr['video_id'] = $id;
                    $arr['goods_id'] = $goods_id;
                    $arr['add_time'] = date("Y-m-d H:i:s", time());
                    array_push($goods, $arr);
                }
                VideoGoodsRelationModel::addVideoGoodsRelation($goods);
            }
            if (!empty($param['course_ids'])) {
                $course_ids = explode(',', $param['course_ids']);
                $course = [];
                foreach ($course_ids as $course_id) {
                    $arr = [];
                    $arr['video_id'] = $id;
                    $arr['course_id'] = $course_id;
                    $arr['add_time'] = date("Y-m-d H:i:s", time());
                    array_push($course, $arr);
                }
                VideoCourseRelationModel::addVideoCourseRelation($course);
            }
            //相关用户
            if (!empty($param['user_ids'])) {
                $user_ids = explode(',', $param['user_ids']);
                $user = [];
                foreach ($user_ids as $user_id) {
                    $arr = [];
                    $arr['video_id'] = $id;
                    $arr['user_id'] = $user_id;
                    $arr['add_time'] = date("Y-m-d H:i:s", time());
                    array_push($user, $arr);
                }
                VideoUserRelationModel::addVideoRelation($user);
            }

            if (($param['chap_title'] && ($param['chap_url']))) {
                VideoChapterModel::delVideoChapterWhere([['video_id', '=', $id]]);
                foreach ($param['chap_title'] as $k => $item) {
                    $chapter_arr = array(
                        'video_id' => $id,
                        'title' => !empty($param['chap_title'][$k]) ? $param['chap_title'][$k] : "",
                        'url' => !empty($param['chap_url'][$k]) ? $param['chap_url'][$k] : "",
                        'img' => !empty($param['chap_img'][$k]) ? $param['chap_img'][$k] : "",
                        'duration' => !empty($param['chap_duration'][$k]) ? $param['chap_duration'][$k] : "",
                        'play_num' => !empty($param['chap_play_num'][$k]) ? $param['chap_play_num'][$k] : 0,
                        'is_free' => !empty($param['chap_is_free'][$k]) ? 1 : 0,
                        'up_time' => date('Y-m-d H:i:s', time()),
                        'add_time' => date('Y-m-d H:i:s', time()),
                        'sort' => !empty($param['chap_sort'][$k]) ? $param['chap_sort'][$k] : 0,
                    );
                    $result = VideoChapterModel::addVideoChapter($chapter_arr);
                    if (empty($result)) {
                        Db::rollback();
                        return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
                    }
                }
            }
            Db::commit();
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } catch (\Exception $e) {
            Db::rollback();
            var_dump($e->getMessage());
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function delVideo(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        //开启事务
        Db::startTrans();
        try {
            //中间逻辑代码
            $flag = VideoModel::delVideoWhere([['id', '=', $id]]);
            if ($flag) {
                VideoCateRelationModel::delVideoCateRelationWhere([['video_id', '=', $id]]);
                VideoGoodsRelationModel::delVideoGoodsRelationWhere([['video_id', '=', $id]]);
                VideoCourseRelationModel::delVideoCourseRelationWhere([['video_id', '=', $id]]);
                VideoChapterModel::delVideoChapterWhere([['video_id', '=', $id]]);
                //提交事务
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "删除成功");
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "删除失败2");
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, $e, "删除失败1");
        }
    }

    /**
     * 获取商品
     * @param Request $request
     * @return array
     */
    public function getGoodsAll(Request $request)
    {
        $param = $request->param();
        $goods_ids = [];
        if (!empty($param['video_id'])) {
            $list = VideoGoodsRelationModel::getVideoGoodsRelationWhereMore([['video_id', '=', $param['video_id']]]);
            if (!empty($list)) {
                foreach ($list as $item) {
                    array_push($goods_ids, $item['goods_id']);
                }
            }
        }

        $list = GoodsModel::getGoodsWhereMore([['is_show', '=', 1], ['is_del', '=', 0]], 'id,good_name');
        $data = [];
        foreach ($list as $item) {
            $arr['name'] = $item['good_name'];
            $arr['value'] = $item['id'];
            if (!empty($goods_ids)) {
                if (in_array($item['id'], $goods_ids)) {
                    $arr['selected'] = true;
                } else {
                    $arr['selected'] = false;
                }
            } else {
                $arr['selected'] = false;
            }
            array_push($data, $arr);
        }
        return Util::returnJson(self::CODE_SUCCESS, $data);
    }

    /**
     * 获取用户
     * @param Request $request
     * @return array
     */
    public function getUserAll(Request $request)
    {
        $param = $request->param();
        $goods_ids = [];
        if (!empty($param['video_id'])) {
            $list = VideoUserRelationModel::getVideoGoodsRelationWhereMore([['video_id', '=', $param['video_id']]]);
            if (!empty($list)) {
                foreach ($list as $item) {
                    array_push($goods_ids, $item['user_id']);
                }
            }
        }
        $list = UserModel::getUserWhereMores([['is_show', '=', 1], ['is_del', '=', 0]], 'id,account');
        $data = [];
        foreach ($list as $item) {
            $arr['name'] = $item['account'];
            $arr['value'] = $item['id'];
            if (!empty($goods_ids)) {
                if (in_array($item['id'], $goods_ids)) {
                    $arr['selected'] = true;
                } else {
                    $arr['selected'] = false;
                }
            } else {
                $arr['selected'] = false;
            }
            array_push($data, $arr);
        }
        return Util::returnJson(self::CODE_SUCCESS, $data);
    }

    /**
     * 获取课程
     * @param Request $request
     * @return array
     */
    public function getCourseAll(Request $request)
    {
        $param = $request->param();
        $course_ids = [];
        if (!empty($param['video_id'])) {
            $list = VideoCourseRelationModel::getVideoCourseRelationWhereMore([['video_id', '=', $param['video_id']]]);
            if (!empty($list)) {
                foreach ($list as $item) {
                    array_push($course_ids, $item['course_id']);
                }
            }
        }

        $list = CourseModel::getCourseWhereMore([['is_show', '=', 1], ['is_del', '=', 0]], 'id,title');
        $data = [];
        foreach ($list as $item) {
            $arr['name'] = $item['title'];
            $arr['value'] = $item['id'];
            if (!empty($course_ids)) {
                if (in_array($item['id'], $course_ids)) {
                    $arr['selected'] = true;
                } else {
                    $arr['selected'] = false;
                }
            } else {
                $arr['selected'] = false;
            }
            array_push($data, $arr);
        }
        return Util::returnJson(self::CODE_SUCCESS, $data);
    }

}